
const simplifyHTML = (htmlString) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(htmlString, 'text/html');
    // 定义不处理的标签
    const ignoredTags = ['table', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'li'];
    function processNode(node) {
        if (node.nodeType === Node.ELEMENT_NODE) {
            const tagName = node.tagName.toLowerCase();
            if (ignoredTags.includes(tagName)) {
                // 保留 table 标签，不做任何处理
                return [node.outerHTML];
            } else if (tagName === 'img') {
                const src = node.getAttribute('src') || '';
                return [`<img src="${src}">`];
            } else {
                // 处理其他标签，递归处理子节点
                let innerContent = [];
                for (const child of node.childNodes) {
                    innerContent.push(...processNode(child));
                }
                // 将子节点的内容合并为一个字符串
                const content = innerContent.join('');
                // 如果当前标签是 p，直接返回其内容
                if (tagName === 'p') {
                    return [`<p>${content}</p>`];
                } else {
                    // 其他标签的内容直接返回，不包裹额外的 p 标签
                    return [content];
                }
            }
        } else if (node.nodeType === Node.TEXT_NODE) {
            // 处理文本节点，去除首尾空白
            const text = node.textContent.trim();
            return text ? [text] : [];
        }
        return [];
    }

    // 处理文档的根节点
    const result = [];
    for (const node of doc.body.childNodes) {
        result.push(...processNode(node));
    }

    // 将结果拼接为最终的 HTML 字符串
    return result.join('').replace(/<\/p><p>/g, '</p>\n<p>');
}

const estimateTokenCount = (text) => {
    let tokenCount = 0;
    
    for (let char of text) {
        if (/[\u4e00-\u9fff]/.test(char)) {
            tokenCount += 0.6;
        } else if (/[a-zA-Z0-9\s]/.test(char)) {
            tokenCount += 0.3;
        } else {
            tokenCount += 1;
        }
    }
    return Math.ceil(tokenCount);
}
/**
 * 查找父级
 */
const parents = (element, selector) => {
    var parentsArray = [];

    while (element.parentElement) {
        element = element.parentElement;
        if (element.matches(selector)) {
            parentsArray.push(element);
        }
    }

    return parentsArray;
}

const generateUniqueId = () => {
        const timestamp = new Date().getTime();
        const randomNum = (Math.random() * 0xffffffff).toString(36);
        const timeStr = timestamp.toString(36);
        return timeStr + randomNum;
}

const unwrapSingleParentImgs = () => {
    Array.from(document.getElementsByTagName('img')).forEach(img => {
        let current = img;
        while (true) {
            const parent = current.parentElement;
            if (!parent || ['BODY', 'HTML', 'HEAD'].includes(parent.tagName)) break;
            if (parent.children.length !== 1) break;
            if (parent.firstElementChild !== current) break;
            const grandParent = parent.parentElement;
            if (grandParent) {
                grandParent.insertBefore(current, parent);
                parent.remove();
            } else {
                break;
            }
        }
    });
}
export {
    simplifyHTML,
    estimateTokenCount,
    generateUniqueId,
    unwrapSingleParentImgs,
    parents
}
